package uk.ac.cam.echo.reader;

/**
 * @author Andrius Dagys
 */

import java.util.HashMap;
import uk.ac.cam.echo.messages.UserMessage;

public class DBCache {
	private Client client;
	private HashMap<String, UserMessage> cache;
	
	public DBCache(Client c){
		this.client = c;
	}
	/**
	 * Retrieves the user data from the server and updates the cache
	 */
	public void refresh() {
		try {
			HashMap<String, UserMessage> newCache = client.getUserTable();
			this.cache = newCache;
		} catch (Exception e){
			System.err.println("Could not update the cache.");
			e.printStackTrace();
		}
		if (cache != null) System.out.println("Successfully refreshed cache");
	}
	/**
	 * Validates a tag - returns user forename and surname if found  
	 * @param tag
	 * @return
	 * @throws UserNotFoundException
	 */
	public String getUserInfo(String tag) throws UserNotFoundException{
		UserMessage userDetails = cache.get(tag);
		if (userDetails == null) throw new UserNotFoundException();
		String name = userDetails.getForename() + " " +
					  userDetails.getSurname();
		return name;
	}
}
